package com.firexxx.vp.domain.audio;

import com.firexxx.vp.infrastructure.file.NFSWrapper;
import com.firexxx.vp.utils.ConfigUtil;
import com.firexxx.vp.utils.FileUtil;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2019/12/19 10:01
 */
@Embeddable
@Data
public class AudioStorage {

    private static String localHostName = null;

    static {
        try {
            localHostName = Inet4Address.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

//    public static FastDFSClientWrapper fastDFSClientWrapper = null;

    //音频存储的主机名
    @NotNull
    @Column(name = "server_name")
    private String serverName;

    //音频本地存储的路径
    @NotNull
    @Column(name = "local_path")
    private String localPath;

    //音频网络存储的路径
    @NotNull
    @Column(name = "web_path")
    private String webPath;

    public byte[] load(String channelId, String stbKey, String filename) {
        return NFSWrapper.download(webPath, "/" + channelId + "/"
                + stbKey + "/" + filename);
//        try {
//            return FileUtil.readAllBytes(localPath + "/" + stbKey + "/" + filename);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return null;
    }

    public void store(String channelId, String stbKey, String filename, byte[] content) throws IOException {
        FileUtil.writeToFile(localPath + "/" + channelId + "/"
                + stbKey + "/" + filename, content);
    }

    public static AudioStorage cloneDefaultAudioStorage() {
        AudioStorage newAudioStorage = new AudioStorage();

        newAudioStorage.serverName = localHostName;
        newAudioStorage.localPath = ConfigUtil.getValue("audio.storage.localPath");
        newAudioStorage.webPath = ConfigUtil.getValue("audio.storage.webPath");

        return newAudioStorage;
    }
}